import axios from "axios";
import CryptoJS from "crypto-js";
import { getUrlObj } from "../utils/handle";
import md5 from "@/utils/md5";
import { env, apiPhp } from "@/api/root";
const SelfConfig = require("../config");
const ApiCnfig = require("./apiConfig");

const User = SelfConfig.user;
const Version = SelfConfig.version;
const TradeId = SelfConfig.tradeId;
const TradeInsideArr = SelfConfig.tradeInsideArr;
const TradeOutsideArr = SelfConfig.tradeOutsideArr;

axios.defaults.timeout = 60000;

// 请求拦截,设置统一header
axios.interceptors.request.use(
  (config) => {
    if (config.data) {
      config.headers["id"] = config.data.id || 0;
      config.headers["uid"] = uni.getStorageSync("person-id").slice(2) || 0;
      config.headers["platform"] = 1;
    }
    config.headers["Content-Type"] =
      "application/x-www-form-urlencoded;charset=UTF-8";
    if (env == "local") {
      // config.headers["n-d-version"] = ' {"yl1001-boot-career-report":"1.4"}'; //曾辉
      // config.headers["n-d-version"] = ' {"yl1001-boot-career-report":"1.9"}'; //高枫
      config.headers["n-d-version"] = ' {"yl1001-boot-career-report":"31.5"}'; //熊子豪
    }
    config.headers["SecretKey"] = "94cbe78f3bcec8be81d68e7bdfb9ad9b";
    if (config.url.indexOf(".jsp") >= 0) return config;
    if (config.url.indexOf("jobOpen/doUpdateZP") >= 0) {
      config.headers["content-Type"] = "application/json; charset=UTF-8";
      return config;
    }
    if (config.url.indexOf("/zt/rights") >= 0) {
      config.headers["content-Type"] = "application/json; charset=UTF-8";
      return config;
    }
    if (config.url.indexOf("/yl1001") >= 0 && config.method == "get")
      return config;
    //微服务这边的接口全部是JSON模式
    if (config.url.indexOf("/api-") >= 0 && config.method == "post") {
      config.headers["content-Type"] = "application/json; charset=UTF-8";
      config.headers["Origin"] = "https://ylt.yl1001.com";
      return config;
    }
    if (config.url.indexOf("/api.php") >= 0) {
      config.headers["content-Type"] = "application/json; charset=UTF-8";
    }
    if (config.url.indexOf("img3.job1001.com") >= 0) {
      config.headers["content-Type"] = "application/json; charset=UTF-8";
      config.dataType = "json";
      return config;
    }
    let url = (config.data && config.data.url) || config.url;
    let user = url.match(/user=([^&]+)/) && url.match(/user=([^&]+)/)[1];
    let func = url.match(/func=([^&]+)/) && url.match(/func=([^&]+)/)[1];
    let userItem = User.find((ele) => ele.prev === user);
    let tradeItem = TradeInsideArr.find((ele) => ele.name === func);
    if (userItem) {
      url = url.replace(`user=${userItem.prev}`, `user=${userItem.cur}`);
      if (Version) url = url.replace(/version=([^&]+)/, `version=${Version}`);
      if (config.data.url) {
        config.data.url = url;
      } else {
        config.url = url;
      }
    }
    if (tradeItem) {
      let condition = config.data[tradeItem.prop]
        ? JSON.parse(config.data[tradeItem.prop])
        : {};
      condition.tradeid = TradeId;
      config.data[tradeItem.prop] = JSON.stringify(condition);
    }
    if (TradeOutsideArr.indexOf(func) >= 0) {
      config.data.tradeid = TradeId;
    }
    if (TradeId) {
      config.headers["tradeid"] = TradeId;
    }
    return config;
  },
  (err) => {
    return Promise.resolve(err);
  }
);

// 如果切换了网络就会返回空的响应，所以结合切换网络字段处理
function handleSwitchNetworkEmptyResponse(response) {
  const isNetworkChanged = uni.getStorageSync("isNetworkChanged");
  if (!response.status && isNetworkChanged) {
    uni.removeStorageSync("isNetworkChanged");
    const app = getApp() || uni.getApp();
    app.showNetworkLostModal();
  }
}

//获取token等信息
function getWebserviceOldAccessToken(configObj) {
  return new Promise((resolve, reject) => {
    var params = {
      user: configObj["user"],
      pwd: md5(configObj["pwd"]),
      time: new Date().getTime(),
    };

    var url =
      apiPhp +
      "/webservice/index.php?op=init_log&gtype=http&func=getAccessToken";
    return axios
      .post(url, params)
      .then((response) => {
        uni.setStorageSync(
          "webserviceOldAccessToken_" + configObj["user"],
          response["access_token"]
        );
        uni.setStorageSync(
          "webserviceOldSecret_" + configObj["user"],
          response["secret"]
        );
        resolve(1);
      })
      .catch((error) => {
        reject(error);
        reject(0);
      });
  });
}

//  响应拦截
axios.interceptors.response.use(
  (res) => {
    return Promise.resolve(res.data);
  },
  (err) => {
    if (process.env.NODE_ENV === "production") console.error("axios", err);

    if (err.response.status == 400) {
      uni.showToast({
        icon: "none",
        title: err.response.data.status_desc,
        duration: 2000,
      });
    } else {
      // 生成职途报告的时候，会经常超时，所以做一个特殊化的提示处理，在统一处理这里就不提示了
      if (err.response.config.url.indexOf("/createZTReport") == -1) {
        uni.showToast({
          icon: "none",
          title:
            (err.response.data && err.response.data.status_desc) ||
            " 网络出差了，请检查网络设置~",
          duration: 2000,
        });
      }
    }
    return Promise.reject(err);
  }
);

axios.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    var settle = require("axios/lib/core/settle");
    var buildURL = require("axios/lib/helpers/buildURL");
    uni.request({
      method: config.method.toUpperCase(),
      url: buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data && JSON.parse(config.data),
      params: config.params,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete(res) {
        //将返回数据的http://格式的url转换成https://格式的url 
        var jsonStr = JSON.stringify(res.data);
        jsonStr = jsonStr.replace(/http:\/\//g, "https://");
        res.data = JSON.parse(jsonStr);
        
        let response = {
          data: res.data,
          status: res.statusCode,
          errMsg: res.errMsg,
          header: res.header,
          config: config,
        };
        settle(resolve, reject, response);
      },
      fail(err) {
        if (process.env.NODE_ENV === "production") {
          console.error("uni.request", err);
          console.error("config", config);
        }
        uni.showToast({
          icon: "none",
          title: "网络异常" + err.errMsg,
          duration: 2000,
        });
      },
    });
  });
};

function getRealmAndAuthorization(configObj, apiPre, apiPath) {
  var peizhi_name = configObj.peizhiName;
  var user_name = configObj.userName;
  var user_pwd = configObj.userPwd;
  var nonce =
    Math.random().toString(36).substr(2, 10) +
    Math.random().toString(36).substr(2, 6);

  // Math.random().toString(36).substr(2, 10) +
  // Math.random().toString(36).substr(2, 6);
  var nowtime = parseInt(new Date().getTime() / 1000);

  var myURL = apiPre + apiPath;
  var myURL_obj = getUrlObj(myURL);
  var port = myURL_obj.port
    ? myURL_obj.port
    : myURL_obj.protocol == "https:"
    ? "443"
    : "80";

  var host = myURL_obj.hostname;
  var api_path = apiPath;
  var normalizedx = [
    "hawk.1.header",
    nowtime,
    nonce,
    "POST",
    api_path,
    host,
    port,
    "",
    "",
  ];
  var normalized_x = normalizedx.join("\n") + "\n";
  var hash = CryptoJS.HmacSHA256(normalized_x, user_pwd);

  var token = CryptoJS.enc.Base64.stringify(hash);
  var authorization =
    'Hawk id="' +
    user_name +
    '", ts="' +
    nowtime +
    '", nonce="' +
    nonce +
    '", mac="' +
    token +
    '"';

  return { realm: peizhi_name, authorization: authorization };
}

function handleData(data) {
  if (!data) return "";
  if (typeof data === "string") return data;
  let dataStr = "";
  try {
    const keys = Object.keys(data);
    if (keys.length === 0) return "";
    dataStr = keys.reduce((res, item) => {
      if (data[item]) {
        return res + item + "=" + data[item] + "&";
      } else {
        return res;
      }
    }, "");
    return dataStr.slice(0, -1);
  } catch (err) {
    return "";
  }
}

let request = {
  get: function (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, {
          params: params,
        })
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  post: function (url, data) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, data)
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  handleEntropy: function (url) {
    if (process.env.NODE_ENV === "development") {
      const time = +new Date(); //时间戳
      const personId = "114514";
      const key = "1qaz2wsx1001";
      const cks = md5(md5(personId + time) + key);
      const newUrl = `${url}?personId=${personId}&time=${time}&cks=${cks}`;
      return newUrl;
    } else {
      return url;
    }
  },

  // apiPre：接口前缀；
  // configName：相应提供商，对应文件ApiConfig,加密用的，不同平台使用的账号和密码不一样；
  // apiPre：接口前缀；
  // apiPath: 格式是 /{version}/{class}/function；
  // data：接口数据
  // 调用例子：request.webservice('mp', `${apiClusterJava}/api-yp/open/index`, '/rightOpen/getCompanyPersonAll', data);
  webservice: function (configName, apiPre, apiPath, data) {
    return new Promise((resolve, reject) => {
      var configObj = ApiCnfig[configName];
      var { realm, authorization } = getRealmAndAuthorization(
        configObj,
        apiPre,
        apiPath
      );
      var url = apiPre + apiPath;
      axios
        .post(url, data, {
          headers: {
            realm: realm,
            authorization: authorization,
          },
        })
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  webserviceOld: function (configName, apiPath, data, headerConfig) {
    var domain = apiPhp + "/server/api/api.php";
    var path = "/des/index";
    //获取请求的路径
    var opAndFunc = apiPath.split("/");
    var op = opAndFunc[0];
    var func = opAndFunc[1];
    var postdata = {
      config: {
        user: configName,
        op: op,
        func: func,
        option: headerConfig,
      },
      //由于php后端底层接口参数需要按顺序接收，需要将data像表单一样按序拼接处理。
      params: handleData(data),
    };
    return new Promise((resolve, reject) => {
      var isOriginal = false;
      if (
        headerConfig &&
        typeof headerConfig == "object" &&
        headerConfig.hasOwnProperty("isOriginal")
      ) {
        isOriginal = headerConfig["isOriginal"];
      }
      var configObj = ApiCnfig["webuser"];
      var { realm, authorization } = getRealmAndAuthorization(
        configObj,
        domain,
        path
      );
      var url = domain + path;
      axios
        .post(url, postdata, {
          headers: {
            realm: realm,
            authorization: authorization,
          },
        })
        .then((response) => {
          if (isOriginal) {
            resolve(response);
          } else {
            let rs;
            if (!(typeof response === "object" && response !== null)) {
              rs = { status: "OK", code: "200", data: response };
            } else {
              if (response.hasOwnProperty("status")) {
                rs = response;
              } else {
                if (response.hasOwnProperty("pageparam")) {
                  rs = response;
                  rs["status"] = "OK";
                  rs["code"] = "200";
                } else {
                  rs = {
                    status: "OK",
                    code: "200",
                    data: response,
                  };
                }
              }
            }
            resolve(rs);
            // console.log("webserviceOld.response", rs);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default request;
